package model

import (
	"math/rand"
	"sync"
	"time"
)

type MeetingList struct {
	meetings map[int]*Meeting
	mutex    *sync.RWMutex
}

func NewMeetingList() *MeetingList {
	return &MeetingList{
		meetings: make(map[int]*Meeting),
		mutex:    new(sync.RWMutex),
	}
}

// GetMeetings 获取所有会议
func (list *MeetingList) GetMeetings() map[int]*Meeting {
	return list.meetings
}

// CreateAndAddMeeting 创建并且添加会议
func (list *MeetingList) CreateAndAddMeeting(addr Address, limit int) *Meeting {
	list.mutex.Lock()
	defer list.mutex.Unlock()

	// 创建会议
	meetingId := list.generateMeetingId()
	meeting := NewMeeting(meetingId, addr, limit)

	// 将会议添加到列表中
	list.meetings[meetingId] = meeting

	return meeting
}

// GetMeetingById 根据会议号获取会议
func (list *MeetingList) GetMeetingById(id int) *Meeting {
	list.mutex.RLock()
	defer list.mutex.RUnlock()

	return list.meetings[id]
}

// RemoveMeetingById 根据 id 移除会议
func (list *MeetingList) RemoveMeetingById(id int) {
	list.mutex.Lock()
	defer list.mutex.Unlock()

	delete(list.meetings, id)
}

// 生成随机会议号
func (list *MeetingList) generateMeetingId() int {
	// 生成随机数种子
	s := rand.NewSource(time.Now().Unix())
	r := rand.New(s)

	// 生成会议号
	var meetingId int
	for {
		// 生成随机 9 位数字
		meetingId = 100000000 + r.Intn(900000000)

		// 如果会议号重复，则重新生成随机数
		if list.meetings[meetingId] == nil {
			return meetingId
		}
	}
}
